package com.aaa.web.controller; /**
 * @ProjectName java_web _demo_20230303_AllServlet
 * @Author 李江波
 * @Date 2023/03/03 上午 09:33
 * @Version 1.0.0
 * @Description
 */

import com.aaa.web.entity.Emp;
import com.aaa.web.service.emp.EmpServiceImpl;
import com.aaa.web.service.emp.Impl.EmpService;
import com.alibaba.fastjson.JSON;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

// /EmpServlet/*  *通配符 通配任何的字符串  query add toUpdate update delete
@WebServlet(name = "EmpServlet", value = "/EmpServlet/*")
public class EmpServlet extends HttpServlet {
    private EmpService empService = new EmpServiceImpl();
    private SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM-dd");
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取url或者uri
        StringBuffer requestURL = req.getRequestURL();
        //url=localhost:8080/EmpServlet?toUpdate 通过url定位到资源 （河南省郑州市高新区科学大道与长春路交叉口向西200米郑大南门）
        System.out.println("请求的URL = " + requestURL);
        String requestURI = req.getRequestURI();
        //uri = EmpServlet/ToUpdate 只是资源的名称 无法定位到具体资源  （郑州大学）
        System.out.println("请求的URI = " + requestURI);
        //截取字符串。获取执行请求的最后部门字符串  requestMethodName = query add toUpdate update delete其中一个
        String requestMethodName = requestURI.substring(requestURI.lastIndexOf("/") + 1);
        //定义转发路径
        String toGoUri =null;
        String jsonData =null;
        //执行各种方法
        switch(requestMethodName){
            case"login":
                toGoUri = this.login(req, resp);
                break;
            case"empExist":
                toGoUri = this.empExist(req, resp);
                break;
            case "queryPage":
                jsonData =  this.queryPage(req,resp);
                break;
            case "queryById":
                jsonData =  this.queryById(req,resp);
                break;
            case "update":
                try {
                    jsonData =  this.update(req,resp);
                } catch (ParseException e) {
                    throw new RuntimeException(e);
                }
                break;
            case "add":
                try {
                    jsonData =  this.add(req,resp);
                } catch (ParseException e) {
                    throw new RuntimeException(e);
                }
                break;
            case "delete":
                jsonData =  this.delete(req,resp);
                break;
            default:
                break;
        }
        //判断不空
        if (toGoUri!=null){
            //转发
            req.getRequestDispatcher(toGoUri).forward(req,resp);
        }
        if (jsonData!=null){
            //定义返回类型是json 并且支持中文编码
            resp.setContentType("application/json;charset=utf-8");
            PrintWriter out = resp.getWriter();
            out.println(jsonData);
        }
    }

    private String queryById(HttpServletRequest req, HttpServletResponse resp) {
        String empId = req.getParameter("empId");
        Emp emp = empService.queryById(Integer.parseInt(empId));
        System.out.println(emp);
        return JSON.toJSONString(emp);
    }

    private String queryPage(HttpServletRequest req, HttpServletResponse resp) {
        //接受参数  pageNo
        String pageNo = req.getParameter("pageNo");
        String empName = req.getParameter("empName");
        String province = req.getParameter("province");
        //封装查询对象
        Emp queryEmp = new Emp();
        queryEmp.setEmpName(empName);
        queryEmp.setProvince(province);
        //定义数字类型 页面
        int pageNoInt = 0;
        //如果第几页没有传递  给默认值
        if(pageNo==null){
            pageNoInt = 1;
        }else {
            //赋值
            pageNoInt = Integer.valueOf(pageNo);
        }
        //判断是否小于1
        if(pageNoInt<1){
            pageNoInt = 1;
        }
        //定义每页显示数量
        int pageSize = 5;
        //查询分页总数量
        int total = empService.queryTotal(queryEmp);
        if (total==0){
            req.setAttribute("error","没有查询到结果");
        }
        // 计算最大页
        int maxPage = total%pageSize==0?total/pageSize:(total/pageSize+1);
        //判断是否最大页，如果大于最大页，等于最大页
        if(pageNoInt>maxPage){
            pageNoInt = maxPage;
        }
        //执行分页查询数据
        List<Emp> empList = empService.queryByPage(pageNoInt, pageSize, queryEmp);
        System.out.println("empList = " + empList);
        //定义一个返回的map对象
        Map resultMap = new HashMap<>();
        resultMap.put("mapList",empList);
        resultMap.put("pageNo",pageNoInt);
        resultMap.put("total",total);
        resultMap.put("maxPage",maxPage);
        return JSON.toJSONString(resultMap);
    }

    private String empExist(HttpServletRequest req, HttpServletResponse resp) {
        //req.getSession(false) 不新建 不纯在返回空
        HttpSession session = req.getSession(false);
        if (session!=null){
            session.invalidate();
            System.out.println("session销毁" + session);
        }
        return "/login.jsp";
    }

    private String login(HttpServletRequest req, HttpServletResponse resp) {
        String userName = req.getParameter( "userName");
        String password = req.getParameter( "password");
        Emp emp = empService.queryName(userName, password);
        if (emp!=null){
            HttpSession session = req.getSession();
            session.setAttribute("empInfo",emp);
            System.out.println("开启session");
            return "/index.jsp";
        }else {
            req.setAttribute("error","账号或密码错误");
            return "/login.jsp";
        }
    }

    /**
     * 执行添加
     * @param req
     * @param resp
     * @return
     */
    private String add(HttpServletRequest req, HttpServletResponse resp) throws ParseException {
        String empName = req.getParameter("empName");
        String sex = req.getParameter("sex");
        String phoneNum = req.getParameter("phoneNum");
        String province = req.getParameter("province");
        String hireDate1 = req.getParameter("hireDate");
        Date hireDate = ft.parse(hireDate1);
        String deptNo = req.getParameter("deptNo");
        String salary = req.getParameter("salary");
        String password = req.getParameter("password");
        Emp emp = new Emp(empName,sex,phoneNum,province,hireDate,Integer.valueOf(deptNo),Double.valueOf(salary),password);
        System.out.println(emp);
        return empService.add(emp)+"";
    }

    /**
     * 更新
     * @param req
     * @param resp
     * @return
     */
    private String update(HttpServletRequest req, HttpServletResponse resp) throws ParseException {
        String empId = req.getParameter("empId");
        String empName = req.getParameter("empName");
        String sex = req.getParameter("sex");
        String phoneNum = req.getParameter("phoneNum");
        String province = req.getParameter("province");
        String hireDate1 = req.getParameter("hireDate");
        Date hireDate = ft.parse(hireDate1);
        String deptNo = req.getParameter("deptNo");
        String salary = req.getParameter("salary");
        String password = req.getParameter("password");
        Emp emp = new Emp(Integer.valueOf(empId),empName,sex,phoneNum,province,hireDate,Integer.valueOf(deptNo),Double.valueOf(salary),password);
        return empService.update(emp)+"";
    }

    /**
     * 根据编号删除
     * @param req
     * @param resp
     * @return
     */
    private String delete(HttpServletRequest req, HttpServletResponse resp) {
        String empId = req.getParameter("empId");
        return empService.deleteById(Integer.valueOf(empId))+"";
    }
}

